package com.mall.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class PasswordUtil {
	
	/**
	 * 验证密码是否符合规则
	 * @param password
	 * @return 错误信息
	 */
	public static String validPwd(String password){
		if(StringUtils.isBlank(password)){
			return "密码不能为空";
		}
		if(password.length() < 6 || password.length() > 20){
			return "密码由6-20个字符组成";
		}
		if(isAllSameChars(password)){
			return "密码不能为同一字符";
		}
		if(isIncreaseChars(password) || isDecreaseChars(password)){
			return "密码不能是连续的字符";
		}
		Pattern pattern = Pattern.compile("^\\d+$");
		Matcher matcher = pattern.matcher(password);
		if(matcher.matches()){
			return "密码不能是纯数字";
		}
		pattern = Pattern.compile("^[a-zA-Z]+$");
		matcher = pattern.matcher(password);
		if(matcher.matches()){
			return "密码不能是纯字母";
		}
		pattern = Pattern.compile("[s<>;']");
		matcher = pattern.matcher(password);
		if(matcher.matches()){
			return "密码只能由英文、数字及符号组成";
		}
		return null;
	}
	
	/**
	 * 是否所有字符都一样
	 * @param password
	 * @return
	 */
	private static boolean isAllSameChars(String password){
		char ch1 = password.charAt(0);
		for(int i = 1;i < password.length();i++){
			char ch = password.charAt(i);
			if(ch != ch1){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 是否是递增的字符
	 * @param password
	 * @return
	 */
	private static boolean isIncreaseChars(String password){
		char ch1 = password.charAt(0);
		for(int i = 1;i < password.length();i++){
			char ch = password.charAt(i);
			if(ch1 + i != ch){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 是否是递减的字符
	 * @param password
	 * @return
	 */
	private static boolean isDecreaseChars(String password){
		char ch1 = password.charAt(0);
		for(int i = 1;i < password.length();i++){
			char ch = password.charAt(i);
			if(ch1 - i != ch){
				return false;
			}
		}
		return true;
	}

}
